import { constantRoutes } from '@/router';
import Api from '@/api/permissionApi';
import { Message } from 'element-ui';
import { getUserInfo } from '@/utils/auth';
import Layout from '@/layout';
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  oldRoutes: [],
  allPath: []
}

const mutations = {
  SET_ROUTES: (state, obj) => {
    state.addRoutes = obj.old_routes
    state.routes = constantRoutes.concat(obj.routes)
    state.oldRoutes = constantRoutes.concat(obj.old_routes)
    state.allPath = obj.all_path
  }
}

// 记录 三级菜单位置
let san_key = []

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data, key = '') {
  data.forEach((item, index) => {
    // 记录位置
    if (key === '') {
      var position = `${index}`
    } else {
      var position = key + '-' + index
    }
    let menu = {}
    let vue_component

    if (item.vue_component == 'Layout') {
      vue_component = Layout
    } else if (item.vue_component == 'RouterViewKeepAlive') {
      vue_component = 'RouterViewKeepAlive'
    } else {
      vue_component = (resolve) => require([`@/views${item.vue_component}`], resolve)
    }

    let names = item.vue_path.split('/')
    if (item.nodes) {
      if (item.vue_component == 'RouterViewKeepAlive') {
        san_key.push(position)
      }
      menu = {
        path: item.vue_path,
        redirect: item.nodes[0].vue_path,
        name: names.pop(),
        title: item.name,
        component: vue_component,
        hidden: item.vue_hidden == 1 ? false : true,//router菜单显示
        children: [],
        meta: { title: item.name, icon: item.icon, position },

      }
      generaMenu(menu.children, item.nodes, position)
    } else {
      menu = {
        path: item.vue_path,
        name: names.pop(),
        title: item.name,
        component: vue_component,
        hidden: item.vue_hidden == 1 ? false : true,//router菜单显示
        meta: { title: item.name, icon: item.icon, position },
      }
    }
    routes.push(menu)
  })
}

const actions = {
  generateRoutes({ commit }, roles) {
    console.log(new Date().getTime(), 'getUserMenuList')
    return new Promise(resolve => {
      const loadMenuData = []
      const asyncRoutes = []
      Api.getUserMenuList({
        admin_id: getUserInfo().userid
      }).then(res => {
        console.log(res, '权限菜单列表');
        console.log(new Date().getTime(), 'getUserMenuList2')
        if (res.code == '200') {
          Object.assign(loadMenuData, res.data)
          generaMenu(asyncRoutes, loadMenuData)
        }
        // asyncRoutes.push({ path: '*', redirect: '/404', hidden: true })


        let oldRoutes = JSON.parse(JSON.stringify(asyncRoutes))
        let del_path = []
        // 把三级菜单加入到二级菜单中
        san_key.map(item => {
          let ls = item.split('-')
          let childrens = asyncRoutes[ls[0]].children[ls[1]].children
          del_path.push(asyncRoutes[ls[0]].children[ls[1]].path)
          childrens.map(item2 => {
            asyncRoutes[ls[0]].children.push(item2)
          })
        })
        // 删除三级菜单
        san_key.map(item => {
          let ls = item.split('-')

          asyncRoutes[ls[0]].children.map((item, idx) => {
            if (del_path.includes(item.path)) {
              asyncRoutes[ls[0]].children.splice(idx, 1)
            }
          })
        })
        san_key = []
        // 把所有路径取出  跳转时判断用
        let all_path = [];
        asyncRoutes.forEach(item => {
          all_path.push(item.path)
          if (item.children) {
            item.children.forEach(item2 => {
              all_path.push(item2.path)
            })
          }
        })
        commit('SET_ROUTES', {
          routes: asyncRoutes,
          old_routes: oldRoutes,
          all_path
        })
        resolve(asyncRoutes)
      }).catch(error => {
        console.log(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}